#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>

#define MYSQL_HOST "localhost"
#define MYSQL_USER "your_username"
#define MYSQL_PASSWORD "your_password"
#define MYSQL_DATABASE "mydb"

void check_mysql_error(MYSQL *conn) {
    if (mysql_errno(conn)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    }
}

int main() {
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;

    // 初始化连接
    conn = mysql_init(NULL);
    if (conn == NULL) {
        fprintf(stderr, "mysql_init() failed\n");
        exit(1);
    }

    // 连接到数据库
    if (mysql_real_connect(conn, MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, 0, NULL, 0) == NULL) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        mysql_close(conn);
        exit(1);
    }

    printf("Connected to MySQL database!\n");

    // 插入数据
    const char *insert_query = "INSERT INTO students (name, age, gender) VALUES ('Alice', 30, 'Female')";
    if (mysql_query(conn, insert_query)) {
        check_mysql_error(conn);
    } else {
        printf("Insert successful\n");
    }

    // 查询数据
    const char *select_query = "SELECT * FROM students";
    if (mysql_query(conn, select_query)) {
        check_mysql_error(conn);
    }

    // 获取结果集
    res = mysql_store_result(conn);
    if (res == NULL) {
        check_mysql_error(conn);
    }

    // 处理结果集
    while ((row = mysql_fetch_row(res)) != NULL) {
        printf("ID: %s, Name: %s, Age: %s, Gender: %s\n", row[0], row[1], row[2], row[3]);
    }

    // 释放结果集
    mysql_free_result(res);

    // 更新数据
    const char *update_query = "UPDATE students SET age = 31 WHERE name = 'Alice'";
    if (mysql_query(conn, update_query)) {
        check_mysql_error(conn);
    } else {
        printf("Update successful\n");
    }

    // 删除数据
    const char *delete_query = "DELETE FROM students WHERE name = 'Alice'";
    if (mysql_query(conn, delete_query)) {
        check_mysql_error(conn);
    } else {
        printf("Delete successful\n");
    }

    // 关闭连接
    mysql_close(conn);

    return 0;
}